package rainy.file.synchronization.client.channel;

import java.util.HashMap;
import java.util.Map;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import rainy.file.synchronization.client.chat.SimpleChatClientInitializer;
import rainy.file.synchronization.client.exception.MasterCannotReachedException;
import rainy.file.synchronization.config.RainyRunTime;

/**
 * channel
 * 
 * @author dongwenbin
 *
 */
public class ChannelFactory {
	private static final Map<String, Channel> channelContainer = new HashMap<String, Channel>();
	private static String host = RainyRunTime.getStringPropDefine("rainy.master.serverName", "localhost");
	private static int port = RainyRunTime.getIntegerPropDefine("rainy.master.port", 9054);

	public static Channel getCurrentChannel(String type, EventLoopGroup group) {
		if (channelContainer.containsKey(type)) {
			return channelContainer.get(type);
		} else {
			Channel channel = createNewChannel(group);
			if (channel == null) {
				throw new MasterCannotReachedException();
			}
			channelContainer.put(type, channel);
			return channel;
		}
	}

	/**
	 * 创建channel
	 * 
	 * @return
	 */
	private static Channel createNewChannel(EventLoopGroup group) {
		Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class)
				.handler(new SimpleChatClientInitializer());
		for (int i = 0; i < 3; i++) {
			try {
				Channel channel = bootstrap.connect(host, port).sync().channel();
				return channel;
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
				try {
					Thread.sleep(3000);
					System.out.println("Can't connect to server!");
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
		}
		throw new MasterCannotReachedException();
	}
}
